import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

//需要配合以下限制
// WhitelistingTextInputFormatter(RegExp("[0-9.]")),
// LengthLimitingTextInputFormatter(9),
class MoneyTextInputFormatter extends TextInputFormatter {
  @override
  TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) {
    String newvalueText = newValue.text;
    if (newvalueText.contains(' ')) {
      newvalueText = newvalueText.replaceAll(' ', '');
    }

    if (newvalueText == ".") {
      //第一个数为.
      newvalueText = "0.";
    } else if (newvalueText.contains(".")) {
      if (newvalueText.lastIndexOf(".") != newvalueText.indexOf(".")) {
        //输入了2个小数点
        newvalueText = newvalueText.substring(0, newvalueText.lastIndexOf('.'));
      } else if (newvalueText.length - 1 - newvalueText.indexOf(".") > 2) {
        //输入了1个小数点 小数点后两位
        newvalueText = newvalueText.substring(0, newvalueText.indexOf(".") + 3);
      }
    }
    if (oldValue.text == '0' && newvalueText.isNotEmpty) {
      if (newvalueText == '00') {
        newvalueText = '0';
      } else if (newvalueText != '0.' && newvalueText != '00') {
        newvalueText = newvalueText.substring(1);
      }
    }

    return TextEditingValue(
      text: newvalueText,
      selection: new TextSelection.collapsed(offset: newvalueText.length),
    );
  }
}

class PositiveTextInputFormatter extends TextInputFormatter {
  @override
  TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) {
    String newvalueText = newValue.text;
    if (newvalueText.contains(' ')) {
      newvalueText = newvalueText.replaceAll(' ', '');
    }

    if (newvalueText.length > 0 && int.parse(newvalueText) == 0) {
      newvalueText = "";
    }

    return TextEditingValue(
      text: newvalueText,
      selection: new TextSelection.collapsed(offset: newvalueText.length),
    );
  }
}

class NoSpaceTextInoutFormatter extends TextInputFormatter {
  @override
  TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) {
    String newvalueText = newValue.text;
    if (newvalueText.contains(' ')) {
      newvalueText = newvalueText.replaceAll(' ', '');
    }
    return TextEditingValue(
      text: newvalueText,
      selection: new TextSelection.collapsed(offset: newvalueText.length),
    );
  }
}
